package com.wanmait.computershop.webController;

import com.wanmait.computershop.dao.CartDAO;
import com.wanmait.computershop.dao.OrderConfirmDAO;
import com.wanmait.computershop.dao.OrderDAO;
import com.wanmait.computershop.dao.OrderDetleDAO;
import com.wanmait.computershop.vo.Address;
import com.wanmait.computershop.vo.Cart;
import com.wanmait.computershop.vo.Torder;
import com.wanmait.computershop.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("web")
public class OrderConfirmController {

    @GetMapping("orderConfirm")
    public String orderConfirm(int ckitem[], Model model, HttpSession session)
    {
        User loginUser = (User)session.getAttribute("loginUser");
        model.addAttribute("orderConfirmDefaultAddress",OrderConfirmDAO.selectDefaultByUid(loginUser.getId()));
        model.addAttribute("orderConfirmAddressList", OrderConfirmDAO.selectNotDefaultByUid(loginUser.getId()));
        List<Cart> checkedCartList = new ArrayList<>();
        for (int i=0;i<ckitem.length;i++)
        {
            Cart cart = CartDAO.selectById(ckitem[i]);
            checkedCartList.add(cart);
        }
        model.addAttribute("checkedCartList",checkedCartList);
        return "web/orderConfirm";
    }

    @GetMapping("addOrder")
    public String addOrder(String aid,Integer[] cartProductId,HttpSession session,Integer[] cartBuyNum)
    {
        Torder torder = new Torder();
        Address address = OrderConfirmDAO.selectByAid(Integer.parseInt(aid));
        User loginUser = (User)session.getAttribute("loginUser");
        torder.setUid(loginUser.getId());
        torder.setUser(loginUser);
        torder.setProvinceName(address.getProvinceName());
        torder.setCityName(address.getCityName());
        torder.setAreaName(address.getAreaName());
        torder.setDetailName(address.getDetail());
        torder.setRecvName(address.getName());
        torder.setOrderPhone(address.getPhone());
        String orderNum = "";
        for (int i = 0; i < 10; i++) {
            Random random = new Random();
            Integer temp = random.nextInt(10);
            String t = temp.toString();
            orderNum = orderNum+t;
        }
        torder.setOrderNum(orderNum);
        OrderDAO.insertOrder(torder);
        Torder torder1 = OrderDAO.selectByOrderNum(orderNum);
        for (int i = 0; i < cartProductId.length; i++)
        {
            OrderDetleDAO.insertByOidAndPidAndNum(torder1.getId(),cartProductId[i],cartBuyNum[i]);
        }
        return "web/payment";
    }


}
